package com.hipac.qs.executors;

import com.hipac.qs.timer.MyTimerTask;

import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author xiaogu
 * @date 2017/8/1 上午12:06
 */
public class ExecutorExsample {
    public static void main(String[] args) {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(10);

        System.out.println(new Date());

        // 从现在开始 2 秒钟之后，每隔 2 秒钟执行一次 job2
        pool.scheduleAtFixedRate(new MyTimerTask("job2"), 2, 2, TimeUnit.SECONDS);

        // 10秒后执行
        pool.schedule(new MyTimerTask("job3 10 second delay"), 10, TimeUnit.SECONDS);

        // 从现在开始 1秒钟后初始化任务 任务会在5秒钟后执行
        pool.scheduleWithFixedDelay(new MyTimerTask("job4 assign date"), 1,5, TimeUnit.SECONDS);

        // 13秒后执行 job5并抛出异常
        pool.schedule(new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("execute job5 will throw RuntimeException" + new Date());
                if (1 == 1 ) {
                    throw new RuntimeException();
                }
                return "job5";
            }
        }, 13, TimeUnit.SECONDS);
    }
}
